import glob
import os
import shutil
import threading
import time
from datetime import datetime

import pycurl
from PyQt6 import sip
from PyQt6.QtCore import Qt, QDir, QFile, QItemSelection, QItemSelectionModel, \
    QCoreApplication, QThread, pyqtSignal, QTimer, QMetaObject  # 添加 QItemSelection 和 QItemSelectionModel 的导入
from PyQt6.QtWidgets import QMainWindow, QMessageBox, QTableWidgetItem, QTableWidget, QAbstractItemView, QFileDialog, \
    QLabel, QDialog, QVBoxLayout, QTextEdit, QPushButton, QApplication, QDialogButtonBox, QLineEdit
from PyQt6.uic import loadUi
import json
from PyQt6.QtGui import QStandardItemModel, QStandardItem, QCursor, QIcon, QAction  # 导入必要的模块，包括QAction
import configparser
from loguru import logger

import MyMessageBox
import Global
from Res.Resources import Resources

from Script.GameFun import GameFun

from UI.ConfigDialog_Logic import ConfigDialog
from UI.DataDialog_Logic import DataDialog
from UserManager import UserManager
from 线程.HeartThread import HeartThread
from 线程.ProcessPoolTask import ProcessPoolTask
from 线程.TableViewThread import TableViewThread
from NetManager.NetWork import NetWork
from UI.MainWindow import Ui_MainWindow
import sys
from UI.CardManagerDialog import CardManagerDialog
from 数据库.DbManager import DbManager

from .BindAccount_Logic import BindAccount
from .CommTableModel import CommTableModel
from .CustomTableModel import CustomTableModel
from .GlobalConfig_Logic import GlobalConfig


class MainWindow(QMainWindow, Ui_MainWindow):
    status_bar_updates = pyqtSignal(dict)  # 定义状态栏更新信号
    mail_imported_signal = pyqtSignal()  # 定义邮箱导入完成信号
    account_imported_signal = pyqtSignal()  # 定义账号导入完成信号
    
    def __init__(self):
        super().__init__()
        try:
            # 加载UI文件
            self.setupUi(self)
            self.heart = None
            # 添加加载状态标志
            self._is_loading = False
            self.account_table={
                "header":["序号", "账号", "密码","UUID",  "邮箱", "邮箱密码", "状态", "区服",'名称','等级', "卡片", "资源", "备注", "上传ID","更新时间"],
                "fields":['id', 'user', 'pass','user_id', 'mail', 'mail_pass','flag','country','name','level','card_name', 'source_info', 'notes','upload_id','update_time'],
                "mail_header": ["序号", "账号", "密码", "状态"],
                "mail_fields": ['id', 'mail', 'mail_pass','flag']
            }



            Global.G_Log = Global.create_file_logger("app", "Log/app.log")
            Global.LOGD("启动中控")
            self.base_dir = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
            ico_path = os.path.join(self.base_dir, "dog.ico")
            icon = QIcon(ico_path)
            self.setWindowIcon(icon)


            self.BindAccount_pro = None

            file_path = "Update.dat"
            default_content = {"appVersion":GameFun.appVersion,"DLCVersion":GameFun.DLCVersion}
            if not os.path.exists(file_path):
                try:
                    with open(file_path, 'w', encoding='utf-8') as file:
                        file.write(json.dumps(default_content,indent=4))
                except IOError as e:
                   pass
            if os.path.exists(file_path):
                fileData=None
                with open(file_path, 'r', encoding='utf-8') as file:
                    fileData = json.load(file)
                if fileData:
                    GameFun.appVersion = fileData.get('appVersion', GameFun.appVersion)
                    GameFun.DLCVersion = fileData.get('DLCVersion', GameFun.DLCVersion)



            # 初始化model
            self.model = CustomTableModel()  # 使用自定义表格模型
            self.model_account = CommTableModel()  # 账号表格
            cffile = QFile('Console.cfg')
            if cffile.exists() == False:
                QMessageBox.warning("错误", "Console.cfg文件不存在")
                QCoreApplication.exit()
                return
            # 读取配置文件，指定编码为utf-8
            with open('Console.cfg', 'r', encoding='utf-8') as file:
                try:
                    Global.G_Config = json.load(file)
                except json.JSONDecodeError:
                    Global.G_Config = {}  # 如果不是合法的 JSON，初始化为空字典
            if os.path.exists("GlobalConfig.cfg"):
                with open('GlobalConfig.cfg', 'r', encoding='utf-8') as file:
                    try:
                        Global.G_GlobalConfig = json.load(file)
                    except json.JSONDecodeError:
                        Global.G_GlobalConfig = {}  # 如果不是合法的 JSON，初始化为空字典

            self.setWindowTitle(Global.G_Config.get("title", "默认标题"))
            self.resize(Global.G_Config.get("softwidth", 800), Global.G_Config.get("softheight", 600))

            # 重新连接信号和槽函数
            self.btn_SelectAll.clicked.connect(self.btn_SelectAll_clicked)
            self.btn_UnSelectAll.clicked.connect(self.btn_UnSelectAll_clicked)
            self.btn_Start.clicked.connect(self.btn_Start_clicked)
            self.btn_Stop.clicked.connect(self.btn_Stop_clicked)
            self.Btn_GetFilePath.clicked.connect(self.Btn_GetFilePath_clicked)
            self.action功能设定.triggered.connect(self.on_function_setting)
            self.actionAPI.triggered.connect(self.on_api)
            self.action开始脚本.triggered.connect(self.on_start_script)
            self.action停止脚本.triggered.connect(self.on_stop_script)
            # self.Btn_CardManager.clicked.connect(self.show_card_manager_dialog)
            self.ck_EnableLog.clicked.connect(self.EnableLog_click)
            self.Btn_LoginCard.clicked.connect(self.Btn_LoginCard_clicked)
            self.Edit_Card.textChanged.connect(self.on_card_changed)
            self.Btn_UnBindCard.clicked.connect(self.Btn_UnBindCard_clicked)
            self.Edit_MaxNum.textChanged.connect(self.on_max_num_changed)
            self.pushButton_BindAccount.clicked.connect(self.BindAccount_Clicked)

            self.pushButton_GlobalConfig.clicked.connect(self.on_global_config)
            self.btn_importAccount.clicked.connect(self.on_importAccount_clicked)

            # 账号中的按钮
            self.pushButton_UseAccount.clicked.connect(self.on_UseAccount_clicked)
            self.pushButton_RunAccount.clicked.connect(self.on_RunAccount_clicked)
            self.pushButton_SuccessAccount.clicked.connect(self.on_SuccessAccount_clicked)
            self.pushButton_FailAccount.clicked.connect(self.on_FailAccount_clicked)
            self.pushButton_UploadAccount.clicked.connect(self.on_UploadAccount_clicked)
            self.pushButton_mailAccount.clicked.connect(self.on_mailAccount_clicked)

            self.action_import.triggered.connect(self.on_action_import)
            self.action_selectAll.triggered.connect(self.on_action_selectAll)
            self.action_UnselectAll.triggered.connect(self.on_action_UnselectAll)
            self.action_del.triggered.connect(self.on_action_del)
            self.action_copy_hang.triggered.connect(self.on_action_copy_hang)
            self.action_clearn.triggered.connect(self.on_action_clearn)
            
            # 添加导出文件菜单项
            #self.action_export_file = QAction("导出文件", self)
            self.action_export_file.triggered.connect(self.on_action_export_file)
            #self.account_menu.addAction(self.action_export_file)
            self.action_Export_All_Del.triggered.connect(self.on_action_export_All_Del)
            self.action_useAccount.triggered.connect(self.on_action_useAccount)
            self.action_runAccount.triggered.connect(self.on_action_runAccount)
            self.action_successAccount.triggered.connect(self.on_action_successAccount)
            self.action_failAccount.triggered.connect(self.on_action_failAccount)
            self.action_uploadAccount.triggered.connect(self.on_action_uploadAccount)
            self.action_uploadAccount.triggered.connect(self.on_action_uploadAccount)

            # 连接邮箱导入信号
            self.mail_imported_signal.connect(self.refresh_mail_view)
            
            # 连接账号导入信号
            self.account_imported_signal.connect(self.refresh_account_view)

            max_num = Global.read_ini(Global.ConfigFileName, 'System', 'maxnum', str(QThread.idealThreadCount()))
            self.Edit_MaxNum.setText(max_num)
            if int(max_num) > 0:
                Global.G_ProcessPool.setMaxThreadCount(int(max_num))

            self.tableView.setAcceptDrops(True)

            file_path = Global.read_ini(Global.ConfigFileName, 'System', '账号', '')
            self.Edit_Path.setText(file_path)
            self.init_table_view()

            enableLog = Global.read_ini(Global.ConfigFileName, 'System', '日志', False)
            self.ck_EnableLog.setChecked(enableLog)
            Global.G_EnableLog = enableLog

            # 隐藏顶部菜单
            self.menuBar.setVisible(False)
            # 设置右键菜单
            #self.tableView.customContextMenuRequested.connect(self.show_context_menu)
            self.tableView_account.customContextMenuRequested.connect(self.show_account_menu)
            # 添加双击事件
            # self.tableView.doubleClicked.connect(self.on_table_view_double_clicked)

            # Global.G_Server = NetWork(Global.G_Config["port"])
            # isNetSuccess = Global.G_Server.startServer()
            # 绑定窗口关闭事件
            self.closeEvent = self.on_close_event

            # 初始化状态栏
            self.init_status_bar(False)


            # 连接状态栏更新信号
            self.status_bar_updates.connect(self.update_status_bar)
            # 使用事件过滤器来监听焦点变化
            self.tableView.installEventFilter(self)
            # 初始化国家选择控件
            self.init_country_combo()
            # 读取配置并设置默认选中项
            self.load_country_from_config()

            self.tableViewThread = TableViewThread()
            # 连接表格更新信号
            self.tableViewThread.update_table_signal.connect(self.on_update_table)
            self.tableViewThread.start()  # 启动线程
            # 延迟调用登录验证，确保所有组件都已初始化
            QCoreApplication.processEvents()

            # 连接滚动条信号
            scroll_bar = self.tableView.verticalScrollBar()
            scroll_bar.valueChanged.connect(self.on_scroll_value_changed)

            self.init_comboBox_mode()
            card = Global.read_ini(Global.ConfigFileName, 'System', 'card', '')
            self.Edit_Card.setText(card)
            mode = Global.read_ini(Global.ConfigFileName, 'System', '模式', 0)
            index = self.comboBox_mode.findData(mode)
            if index == -1:
                if self.comboBox_mode.count() > 0:
                    self.comboBox_mode.setCurrentIndex(0)
            else:
                self.comboBox_mode.setCurrentIndex(index)

            self.btn_Start.setEnabled(False)
            self.btn_Stop.setEnabled(False)
            self.pushButton_BindAccount.setEnabled(False)
            self.pushButton_GlobalConfig.setEnabled(False)
            self.btn_importAccount.setEnabled(False)


            self.pushButton_UseAccount.setEnabled(False)
            self.pushButton_FailAccount.setEnabled(False)
            self.pushButton_SuccessAccount.setEnabled(False)
            self.pushButton_RunAccount.setEnabled(False)
            self.pushButton_UploadAccount.setEnabled(False)
            self.pushButton_mailAccount.setEnabled(False)

            self.init_Dbc_data()
            port = Global.G_Config.get("port")
            # Global.G_Server = NetServer(port)
            # Global.G_Server.Start()
            self.init_account_table_view()
            #AccountManager.读取所有账号数据()
            UserManager.initialize()
        except Exception as e:
            Global.LOGE(f"启动异常:{e}")

    def init_comboBox_mode(self):
        # 读取Country.json文件
        try:
            Mode_path = Resources.GetFilePath("Res/Mode.json")
            if os.path.exists(Mode_path):
                with open(Mode_path, 'r', encoding='utf-8') as file:
                    datas = json.load(file)
                    for item in datas:
                        if item['enable']:
                            self.comboBox_mode.addItem(item['display'], item['value'])
        except Exception as e:
            QMessageBox.critical(self, "错误", f"加载模式错误: {str(e)}")

        # 连接选择事件
        self.comboBox_mode.currentIndexChanged.connect(self.on_mode_changed)

    def on_mode_changed(self, index):
        if index >= 0:
            value = self.comboBox_mode.itemData(index)
            Global.write_ini(Global.ConfigFileName, 'System', '模式', value)

    def on_update_table(self):
        """处理表格更新信号"""
        # 这个方法会被TableViewThread的update_table_signal触发
        # 实际的数据更新已经在线程中完成，这里只需要应用待处理的更新
        if hasattr(self, 'model') and self.model is not None:
            # 确保UI线程中应用更新
            self.model.applyPendingUpdates()
            # 强制更新视图
            self.tableView.viewport().update()

    def on_scroll_value_changed(self, value):
        """处理滚动条值变化事件"""
        if hasattr(self, 'model') and self.model is not None:
            # 获取当前可见行范围
            rect = self.tableView.viewport().rect()
            top_index = self.tableView.indexAt(rect.topLeft())
            bottom_index = self.tableView.indexAt(rect.bottomLeft())

            if top_index.isValid() and bottom_index.isValid():
                # 更新模型中的可见行范围
                self.model.updateVisibleRows(top_index.row(), bottom_index.row())

    def update_visible_rows(self):
        """更新当前可见的表格行范围"""
        if not hasattr(self, 'model') or self.model is None or not hasattr(self, 'tableView'):
            return

        try:
            # 获取表格视图的可见区域
            viewport = self.tableView.viewport()
            rect = viewport.rect()

            # 获取第一个可见行
            top_index = self.tableView.indexAt(rect.topLeft())
            if not top_index.isValid():
                top_row = 0
            else:
                top_row = top_index.row()

            # 获取最后一个可见行
            bottom_point = rect.bottomLeft()
            # 向下偏移一点，确保获取到最后一行
            bottom_point.setY(bottom_point.y() - 1)
            bottom_index = self.tableView.indexAt(bottom_point)

            if not bottom_index.isValid():
                # 如果底部索引无效，尝试获取最后一行
                row_count = self.model.rowCount()
                if row_count == 0:
                    return  # 没有数据时不处理
                bottom_row = min(top_row + 20, row_count - 1)  # 默认显示20行或最大行数
            else:
                bottom_row = bottom_index.row()

            # 添加缓冲区，多渲染几行，提高滚动体验
            buffer = 5
            first_visible = max(0, top_row - buffer)
            last_visible = min(self.model.rowCount() - 1, bottom_row + buffer)

            # 确保first_visible不大于last_visible
            if first_visible > last_visible:
                first_visible, last_visible = last_visible, first_visible

            # 只有当可见行范围确实发生变化时才更新
            if (hasattr(self.model, 'first_visible_row') and hasattr(self.model, 'last_visible_row') and
                    (self.model.first_visible_row != first_visible or self.model.last_visible_row != last_visible)):
                # 更新模型中的可见行信息
                self.model.updateVisibleRows(first_visible, last_visible)

        except Exception as e:
            Global.LOGE(f"更新可见行范围时发生错误: {str(e)}")

    def init_Dbc_data(self):
        try:
            def 加载DBC文件(path,filed):
                path = Resources.GetFilePath(path)
                with open(path, 'r', encoding='utf-8') as f:  # 显式指定编码
                    Global.G_Dbc[filed] = json.load(f)

            加载DBC文件("Res/Dbc/phone.json","phone")
            加载DBC文件("Res/Dbc/gacha.json", "gacha")
            加载DBC文件("Res/Dbc/pctable.json", "pctable")
            加载DBC文件("Res/Dbc/pet.json", "pet")
            加载DBC文件("Res/Dbc/currency_etc.json", "currency_etc")
            加载DBC文件("Res/Dbc/collection_book.json", "collection_book")
            加载DBC文件("Res/Dbc/guide_quest_mission.json", "guide_quest_mission")
            加载DBC文件("Res/Dbc/individual_mission.json", "individual_mission")
            加载DBC文件("Res/Dbc/pc_reinforcement_cost.json", "pc_reinforcement_cost")
            加载DBC文件("Res/Dbc/stage_achievement_reward.json", "stage_achievement_reward")
            加载DBC文件("Res/Dbc/pc_evolution_material.json", "pc_evolution_material")
            加载DBC文件("Res/Dbc/conversion.json", "conversion")
        except Exception as e:
            Global.LOGE(f"init_Dbc_data异常: {str(e)}")

    def eventFilter(self, obj, event):
        try:
            if obj == self.tableView or obj == self.tableView_account:
                # 处理按键事件
                if event.type() == event.Type.KeyPress:
                    key_event = event
                    if key_event.key() in (Qt.Key.Key_Enter, Qt.Key.Key_Return):
                        if self.tableView.selectionModel():
                            selected_indexes = self.tableView.selectedIndexes()
                            for index in selected_indexes:
                                if index.isValid():
                                    self.model.setData(index, Qt.CheckState.Checked.value,Qt.ItemDataRole.CheckStateRole)

                        if self.tableView_account.selectionModel():
                            selected_indexes = self.tableView_account.selectedIndexes()
                            for index in selected_indexes:
                                if index.isValid():
                                    self.model_account.setData(index, Qt.CheckState.Checked.value,Qt.ItemDataRole.CheckStateRole)
                        return True
        except KeyboardInterrupt:
            pass
        except Exception as e:
            Global.G_Log(f"事件处理异常: {e}")
        return super().eventFilter(obj, event)

    def mousePressEvent(self, event):
        if event.button() == Qt.MouseButton.LeftButton:
            self.tableView.clearSelection()

    def on_card_changed(self):
        card_value = self.Edit_Card.text()
        Global.write_ini(Global.ConfigFileName, 'System', 'card', card_value)



    def init_table_view(self):
        try:
            Global.G_Game.clear()
            if self.model != None:
                # self.model.removeRows(0,self.model.rowCount())
                self.model.clear()
            # 获取FieldList字段
            field_list = Global.G_Config.get('FieldList', [])

            if field_list:
                # 设置行数和列数
                # self.model.setRowCount(0)
                # self.model.setColumnCount(len(field_list) + 1)

                # 设置表头
                self.model.headers = [{'name': '序号', 'key': 'index'}] + field_list
                # 自动设置列头通过headers属性

            self.tableView.setModel(self.model)
            self.tableView.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)
            self.tableView.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
            self.tableView.setAlternatingRowColors(True)
            self.tableView.setSelectionMode(QAbstractItemView.SelectionMode.MultiSelection)
            self.tableView.verticalHeader().setVisible(False)
            self.tableView.horizontalHeader().setStretchLastSection(True)
            self.tableView.installEventFilter(self)
            self.tableView.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
            self.tableView.show()

            # 设置列宽
            self.tableView.setColumnWidth(0, 50)  # 序号列宽度为50
            for i, field in enumerate(field_list):
                width = field.get('width', 100)  # 默认宽度为100
                self.tableView.setColumnWidth(i + 1, width)
            # 初始化可见行信息
            self.update_visible_rows()


        except FileNotFoundError:
            QMessageBox.critical(self, "错误", "配置文件Console.cfg不存在！")
        except Exception as e:
            QMessageBox.critical(self, "错误", f"初始化表格视图时发生错误: {str(e)}")

    # 导入代理
    def init_Porxy(self):
        proxy_file_path = Global.read_ini(Global.ConfigFileName, 'System', '代理', '')
        proxyFile = QFile(proxy_file_path)
        if proxyFile.exists() == False:
            Global.LOGE(f"代理文件:{proxy_file_path} 不存在")
            return
        with open(proxy_file_path, 'r', encoding='utf-8') as file:
            proxys = file.read()
        proxysText = proxys.splitlines()
        for i in range(len(proxysText)):
            if "#" in proxysText[i] > -1:
                continue
            if '/' in proxysText[i]:
                parts = proxysText[i].split('/')
            if '----' in proxysText[i]:
                parts = proxysText[i].split('----')
            if len(parts) >= 4 and i < len(Global.G_Game):
                Global.G_Game[i].data["proxyIP"] = parts[0]
                Global.G_Game[i].data["proxyPort"] = int(parts[1])
                Global.G_Game[i].data["proxyUser"] = parts[2]
                Global.G_Game[i].data["proxyPass"] = parts[3]
            else:
                break

    def Btn_LoginCard_clicked(self):
        try:
            card_value = Global.read_ini(Global.ConfigFileName, 'System', 'card', '')
            if len(card_value) == 0:
                return
            isSuccess, erro = Global.G_YZ.Login(card_value)
            if isSuccess == False:
                QMessageBox.warning(self, "验证错误", erro)
            else:

                # 启用开始和停止按钮
                self.Btn_LoginCard.setEnabled(False)
                self.Btn_UnBindCard.setEnabled(False)
                self.Edit_Card.setEnabled(False)
                self.btn_Start.setEnabled(True)
                self.btn_Stop.setEnabled(True)
                #self.btn_importAccount.setEnabled(True)

                self.btn_SelectAll.setEnabled(True)
                self.btn_UnSelectAll.setEnabled(True)

                self.pushButton_BindAccount.setEnabled(True)
                self.pushButton_GlobalConfig.setEnabled(True)

                #self.Edit_Path.setEnabled(True)
                #self.Btn_GetFilePath.setEnabled(True)
                # 创建并启动心跳线程
                if not getattr(self, "heart") or self.heart is None:
                    self.heart = HeartThread()
                    self.heart.start()
                else:
                    # 如果已存在心跳线程，先停止旧的再创建新的
                    self.heart.stop()
                    self.heart.wait()
                    self.heart = HeartThread()
                    self.heart.start()
        except Exception as e:
            Global.LOGE(f"[异常]->登陆异常{e}")

    def Btn_UnBindCard_clicked(self):
        reply = QMessageBox.warning(self, '温馨提示', '您正在操作解绑,超出免费解绑次数将扣取时长请确认!',
                                    QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No)
        if reply == QMessageBox.StandardButton.No:
            return  # 用户选择不关闭进程
        card_value = Global.read_ini(Global.ConfigFileName, 'System', 'card', '')
        if len(card_value) == 0:
            return
        isSuccess, erro = Global.G_YZ.UnBindCard(card_value)
        if isSuccess == False:
            QMessageBox.warning(self, "解绑失败", erro)
        else:
            QMessageBox.warning(self, "解绑成功", erro)

    def Btn_GetFilePath_clicked(self):
        file_path, _ = QFileDialog.getOpenFileName(self, "选择文件", "", "账号txt (*.txt)")
        if file_path:
            # 将选择的文件路径显示到 Edit_Path 控件中
            self.Edit_Path.setText(file_path)
            Global.write_ini(Global.ConfigFileName, 'System', '账号', file_path)


    def init_status_bar(self, isNetSuccess):
        # 使用现有的状态栏控件
        # self.statusBar.clearMessage()

        # 添加端口信息
        # port_label = QLabel("端口")
        # port_label.setFixedWidth(60)
        # port_value = QLabel(str(Global.G_Config.get("port", "")))
        # port_value.setFixedWidth(100)
        # if isNetSuccess:
        #     port_value.setStyleSheet("color: green")
        # else:
        #     port_value.setStyleSheet("color: red")
        #     port_value.setText(port_value.text() + " 启动失败")
        # self.statusBar.addWidget(port_label)
        # self.statusBar.addWidget(port_value)

        # 添加版本信息
        version_label = QLabel("版本")
        version_label.setFixedWidth(60)
        version_value = QLabel(Global.G_VER)
        version_value.setFixedWidth(100)
        self.statusBar.addWidget(version_label)
        self.statusBar.addWidget(version_value)

        # 添加到期时间信息
        expire_label = QLabel("到期时间")
        expire_label.setFixedWidth(60)
        self.expire_value = QLabel()
        self.expire_value.setText("")
        self.expire_value.setFixedWidth(120)
        self.statusBar.addWidget(expire_label)
        self.statusBar.addWidget(self.expire_value)

        tj_label = QLabel("产出账号")
        tj_label.setFixedWidth(60)
        self.tj_value = QLabel()
        self.tj_value.setText("")
        self.tj_value.setFixedWidth(80)
        self.statusBar.addWidget(tj_label)
        self.statusBar.addWidget(self.tj_value)

        upload_label = QLabel("上传自选")
        upload_label.setFixedWidth(60)
        self.upload_value = QLabel()
        self.upload_value.setText("")
        self.upload_value.setFixedWidth(80)
        self.statusBar.addWidget(upload_label)
        self.statusBar.addWidget(self.upload_value)

        hour_produce_label = QLabel("时产")
        hour_produce_label.setFixedWidth(60)
        self.hour_produce_value = QLabel()
        self.hour_produce_value.setText("")
        self.hour_produce_value.setFixedWidth(80)
        self.statusBar.addWidget(hour_produce_label)
        self.statusBar.addWidget(self.hour_produce_value)
        # # 添加导入说明信息
        # import_label = QLabel("导入说明")
        # import_label.setFixedWidth(100)
        # import_value = QLabel("拖拽文件名包含 [账号]、[ip] 进行导入账号和代理IP")
        # import_value.setFixedWidth(300)
        # import_value.setStyleSheet("color: red")
        # self.statusBar.addWidget(import_label)
        # self.statusBar.addWidget(import_value)

    def init_country_combo(self):
        # 读取Country.json文件
        try:
            Country_path = Resources.GetFilePath("Res/Country.json")
            if os.path.exists(Country_path):
                with open(Country_path, 'r', encoding='utf-8') as file:
                    countries = json.load(file)
                    for country in countries:
                        self.cb_country.addItem(country['display'], country['country'])
        except Exception as e:
            QMessageBox.critical(self, "错误", f"加载国家数据时发生错误: {str(e)}")

        # 连接选择事件
        self.cb_country.currentIndexChanged.connect(self.on_country_changed)


    def on_country_changed(self, index):
        if index >= 0:
            country_code = self.cb_country.itemData(index)
            Global.write_ini(Global.ConfigFileName, 'System', '国家', country_code)

    def load_country_from_config(self):
        # 从配置中读取国家代码
        country_code = Global.read_ini(Global.ConfigFileName, 'System', '国家', '')
        if country_code:
            index = self.cb_country.findData(country_code)
            if index >= 0:
                self.cb_country.setCurrentIndex(index)
        else:
            if self.cb_country.count() > 0:
                self.cb_country.setCurrentIndex(0)
                self.on_country_changed(0)
            else:
                self.cb_country.setCurrentIndex(-1)

    # 连接Btn_CardManager按钮的点击事件
    def show_card_manager_dialog(self):
        # 创建并显示卡号管理窗口
        card_manager_dialog = CardManagerDialog(self)
        card_manager_dialog.exec()

    def EnableLog_click(self):
        # 获取控件的点击状态
        enable_log = self.ck_EnableLog.isChecked()
        # 修改全局变量
        Global.G_EnableLog = enable_log
        Global.write_ini(Global.ConfigFileName, "System", '日志', enable_log)

    def BindAccount_Clicked(self):
        if self.BindAccount_pro is None or sip.isdeleted(self.BindAccount_pro):
            self.BindAccount_pro = BindAccount()
            self.BindAccount_pro.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose)
            self.BindAccount_pro.show()
        else:
            self.BindAccount_pro.raise_()
            self.BindAccount_pro.activateWindow()

    def resizeEvent(self, event):
        """
        窗口大小调整事件处理函数
        捕获窗口调整后的最终宽度和高度并保存到配置文件
        """
        # 调用父类的resizeEvent方法
        super().resizeEvent(event)

        # 获取调整后的窗口大小
        width = self.width()
        height = self.height()
        Global.G_Config["softwidth"] = width
        Global.G_Config["softheight"] = height

        # 保存配置到文件
        with open('Console.cfg', 'w', encoding='utf-8') as file:
            json.dump(Global.G_Config, file, ensure_ascii=False, indent=4)

    def on_global_config(self):
        """打开全局配置对话框"""
        config_dialog = GlobalConfig()
        config_dialog.exec()

    def dragEnterEvent(self, event):
        # 判断拖拽的内容是否是文件
        if event.mimeData().hasUrls():
            if event.source() == self:
                event.setDropAction(Qt.DropAction.MoveAction)
                event.accept()  # 接受拖拽事件
            else:
                event.acceptProposedAction()
        else:
            event.ignore()

    def on_close_event(self, event):
        # 增加警告提示信息
        reply = QMessageBox.question(self, '温馨提示', '您将要退出是否继续？',
                                     QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No)
        if reply == QMessageBox.StandardButton.No:
            event.ignore()
            return

        Global.G_ProcessPool.clear()
        for game in Global.G_Game:
            game.isScriptRun = False
            # if game.PublicEvent is not None:
            #     game.PublicEvent.set()
            #     game.PublicEvent = None
            if game.GateWay !=None :
                game.GateWay.Close()
            if game.Game !=None :
                game.Game.Close()

        # Global.G_Server.stopServer()
        Global.is_running = False
        # 停止线程
        self.tableViewThread.terminate()
        UserManager.close()
        # # 清理LZ4_Native资源
        # try:
        #     from Script.LZ4_Native import LZ4_Native
        #     LZ4_Native.cleanup()
        # except Exception as e:
        #     Global.LOGD(f"清理LZ4_Native资源时出错: {str(e)}")

        Global.G_Game.clear()
        Global.LOGD("关闭中控")
        # 接受关闭事件
        event.accept()

    def dropEvent(self, event):
        # 判断是否是文件
        if event.mimeData().hasUrls():
            for url in event.mimeData().urls():
                file_path = url.toLocalFile()
                # 获取文件名
                file_name = QFile(file_path).fileName()
                # 判断是否为账号文件
                # if "账号" in file_name:
                #     Global.write_ini(Global.ConfigFileName, 'System', '账号', file_name)
                #     self.Edit_Path.setText(file_name)
                #     self.init_table_view()
                #     # 以线程方式调用init_table_data
                #     self.table_data_thread = self.TableDataThread(self)
                #     self.table_data_thread.start()
                #
                # # 判断文件名是否包含 "ip"（不区分大小写）
                # elif "ip" in file_name.lower():
                #     Global.write_ini(Global.ConfigFileName, 'System', '代理', file_name)
                #     self.init_Porxy()
            event.acceptProposedAction()

    def on_max_num_changed(self):
        max_num = self.Edit_MaxNum.text()
        Global.write_ini(Global.ConfigFileName, 'System', 'maxNum', max_num)

    def show_context_menu(self, pos):
        index = self.tableView.indexAt(pos)
        self.m_currentRow = self.tableView.rowAt(pos.y())
        if index.isValid():
            directory = QDir("config")
            if directory.exists():
                # 清空现有的二级菜单项
                self.configmenu.clear()

                # 遍历 config 文件夹中的文件
                for file_info in directory.entryInfoList(QDir.Filter.Files):
                    file_name = file_info.fileName()
                    # 创建一个新的 QAction 并添加到 configmenu
                    action = self.configmenu.addAction(file_name)
                    # 连接槽函数，点击时打印文件名
                    action.triggered.connect(lambda checked, name=file_name: self.on_config_file_selected(name))
        else:
            # 清空选中的行
            self.tableView.clearSelection()
        # 获取鼠标的全局位置
        global_pos = self.tableView.viewport().mapToGlobal(pos)
        # 在鼠标点击的位置显示右键菜单
        self.rightmenu.exec(global_pos)
    def show_account_menu(self,pos):
        if not hasattr(self, 'cur_btn_key') or not self.cur_btn_key or (self.cur_btn_key!='待用账号' and self.cur_btn_key!='邮箱账号'):
            self.action_import.setEnabled(False)
        else:
            self.action_import.setEnabled(True)
            
        # 确保导出菜单项总是可见
        self.action_export_file.setEnabled(hasattr(self, 'cur_btn_key') and bool(self.cur_btn_key))
        if hasattr(self, 'cur_btn_key'):
            if self.cur_btn_key=='邮箱账号':
                self.menu_moveAccount.setEnabled(False)
            else:
                self.menu_moveAccount.setEnabled(True)
            if self.cur_btn_key=='待用账号':
                self.action_useAccount.setEnabled(False)
                self.action_runAccount.setEnabled(True)
                self.action_successAccount.setEnabled(True)
                self.action_failAccount.setEnabled(True)
                self.action_uploadAccount.setEnabled(True)
            elif self.cur_btn_key=='运行账号':
                self.action_useAccount.setEnabled(True)
                self.action_runAccount.setEnabled(False)
                self.action_successAccount.setEnabled(True)
                self.action_failAccount.setEnabled(True)
                self.action_uploadAccount.setEnabled(True)
            elif self.cur_btn_key == '成功账号':
                self.action_useAccount.setEnabled(True)
                self.action_runAccount.setEnabled(True)
                self.action_successAccount.setEnabled(False)
                self.action_failAccount.setEnabled(True)
                self.action_uploadAccount.setEnabled(True)
            elif self.cur_btn_key == '失败账号':
                self.action_useAccount.setEnabled(True)
                self.action_runAccount.setEnabled(True)
                self.action_successAccount.setEnabled(True)
                self.action_failAccount.setEnabled(False)
                self.action_uploadAccount.setEnabled(True)
            elif self.cur_btn_key == '上传账号':
                self.action_useAccount.setEnabled(True)
                self.action_runAccount.setEnabled(True)
                self.action_successAccount.setEnabled(True)
                self.action_failAccount.setEnabled(True)
                self.action_uploadAccount.setEnabled(False)

        headers = self.model_account._headers[1:]
        hang = self.tableView_account.indexAt(pos)
        if hang.isValid():
            self.cur_row=hang.row()
            self.menu_copy_col.clear()
            if not self.menu_copy_col.actions():
                for name in headers:
                    action = self.menu_copy_col.addAction(name)
                    action.triggered.connect(lambda checked, name=name: self.copy_column_value(name))
        self.menu_filter.clear()
        if not self.menu_filter.actions():
            for name in headers:
                action = self.menu_filter.addAction(name)
                action.triggered.connect(lambda checked, name=name: self.filter_column_value(name))#这里互虐了第一列，所以需要加上
         # 获取鼠标的全局位置
        global_pos = self.tableView_account.viewport().mapToGlobal(pos)
        # 在鼠标点击的位置显示右键菜单
        self.account_menu.exec(global_pos)
        
    def copy_column_value(self, column_name):
        """复制指定列的值"""
        #local_pos = self.tableView_account.viewport().mapFromGlobal(QCursor.pos())
        #hang = self.tableView_account.indexAt(pos)
        if self.cur_row>=0:
            # 获取列索引
            column_index = self.model_account._headers.index(column_name)  # 减去序号列
            # 获取单元格数
            index = self.model_account.index(self.cur_row, column_index)
            cell_value = self.model_account.data(index, Qt.ItemDataRole.DisplayRole)
            if not isinstance(cell_value,str) and not cell_value.isValid():
                cell_value=""
            # 复制到剪贴板
            clipboard = QApplication.clipboard()
            clipboard.setText(str(cell_value))
        self.cur_row =-1

    def filter_column_value(self, column_name):
        if hasattr(self, 'cur_btn_key') and self.cur_btn_key:
            try:
                # 获取对应的字段名 - 根据column_name在header中查找索引
                try:
                    # 根据当前视图类型选择正确的header和fields
                    if self.cur_btn_key == "邮箱账号":
                        column_index = self.account_table['mail_header'].index(column_name)
                        if column_index < 0 or column_index >= len(self.account_table['mail_fields']):
                            raise ValueError(f"无效的列索引: {column_index}")
                        field_name = self.account_table['mail_fields'][column_index]
                    else:
                        column_index = self.account_table['header'].index(column_name)
                        if column_index < 0 or column_index >= len(self.account_table['fields']):
                            raise ValueError(f"无效的列索引: {column_index}")
                        field_name = self.account_table['fields'][column_index]
                except (ValueError, IndexError) as e:
                    QMessageBox.warning(self, "错误", f"无法找到列 '{column_name}' 对应的字段名: {str(e)}")
                    return
                
                # 创建过滤条件输入对话框
                dialog = QDialog(self)
                dialog.setWindowTitle(f'过滤 {column_name}')
                dialog.setMinimumWidth(350)
                
                layout = QVBoxLayout()
                
                # 添加提示标签
                label = QLabel(f'请输入 {column_name} 的过滤条件:')
                layout.addWidget(label)
                
                # 添加通配符使用说明（红色文字）
                help_label = QLabel(f'<p>查询方法说明:</p>'
                                   f'<p>1. 精确匹配: 直接输入要查询的内容</p>'
                                   f'<p>2. 模糊查询: 使用 <span style="color:red;">%</span> 作为通配符</p>'
                                   f'<p>   - <span style="color:red;">abc%</span>: 以abc开头的内容</p>'
                                   f'<p>   - <span style="color:red;">%abc</span>: 以abc结尾的内容</p>'
                                   f'<p>   - <span style="color:red;">%abc%</span>: 包含abc的内容</p>'
                                   f'<p>3. 状态 字段: 0 未使用 1 使用中 2 成功  3 失败  4 上传')
                help_label.setStyleSheet("font-size: 10pt;")
                layout.addWidget(help_label)
                
                # 添加输入框
                input_box = QLineEdit()
                layout.addWidget(input_box)
                
                # 添加按钮
                btn_box = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
                btn_box.accepted.connect(dialog.accept)
                btn_box.rejected.connect(dialog.reject)
                layout.addWidget(btn_box)
                
                dialog.setLayout(layout)
                
                # 显示对话框并获取结果
                if dialog.exec() == QDialog.DialogCode.Accepted:
                    filter_value = input_box.text().strip()
                    
                    # 显示加载提示
                    self.statusBar.showMessage(f"正在过滤 {column_name}={filter_value} 的数据，请稍候...")
                    
                    # 设置加载状态
                    self._is_loading = True
                    self.disable_account_buttons()
                    
                    # 清空当前表格
                    self.model_account.clear()
                    
                    # 根据当前按钮状态确定查询的状态值
                    status = None
                    button_info=None
                    if self.cur_btn_key == '待用账号':
                        status = UserManager.STATUS_UNUSED
                        button_info =self.pushButton_UseAccount
                    elif self.cur_btn_key == '运行账号':
                        status = UserManager.STATUS_RUNNING
                        button_info =self.pushButton_RunAccount
                    elif self.cur_btn_key == '成功账号':
                        status = UserManager.STATUS_SUCCESS
                        button_info = self.pushButton_SuccessAccount
                    elif self.cur_btn_key == '失败账号':
                        status = UserManager.STATUS_FAILED
                        button_info = self.pushButton_FailAccount
                    elif self.cur_btn_key == '上传账号':
                        status = UserManager.STATUS_UPLOAD
                        button_info = self.pushButton_UploadAccount
                    elif self.cur_btn_key == '邮箱账号':
                        button_info = self.pushButton_mailAccount
                        # 邮箱账号特殊处理
                        #self._do_filter_mail_accounts(field_name, filter_value, self.account_table['mail_fields'])
                        #return
                    
                    # 构建查询条件
                    conditions = {field_name: filter_value}
                    if self.cur_btn_key =="邮箱账号":
                        QTimer.singleShot(50, lambda: self._do_query_mail_accounts(
                            self.account_table['mail_fields'],
                            button_info,
                            self.cur_btn_key,
                            conditions
                        ))
                    else:
                        # 使用QTimer延迟执行查询，让UI有时间更新
                        QTimer.singleShot(50, lambda: self._do_query_users(
                            status,
                            self.account_table['fields'],
                            button_info,
                            self.cur_btn_key,
                            conditions
                        ))
            except Exception as e:
                Global.LOGE(f"过滤数据时发生错误: {e}")
                self.statusBar.showMessage(f"过滤数据失败: {str(e)}", 3000)
                self._is_loading = False
                self.enable_account_buttons()



    def _do_query_mail_accounts(self, fields, button_obj, button_text, conditions=None):
        """执行邮箱账号查询的方法，支持可选的条件过滤和自定义字段"""
        try:
            # 执行查询
            处理后数据 = UserManager.get_mail_accounts(
                fields=fields,
                conditions=conditions,
                format='list'
            )
            self.model_account.insertRowsWithData(0, 处理后数据)
        except Exception as e:
            Global.LOGE(f"查询邮箱数据异常: {e}")
        finally:
            # 恢复按钮状态
            button_obj.setText(f"{button_text}({len(处理后数据)})")
            self.enable_account_buttons()
            self.statusBar.clearMessage()
            self._is_loading = False

    def on_config_file_selected(self, file_name):
        # 获取当前选中的行号
        selected_indexes = self.tableView.selectedIndexes()
        if selected_indexes:
            # 使用集合去重，确保每行只获取一次
            selected_rows = set(index.row() for index in selected_indexes)
            config = configparser.ConfigParser()
            config.read('bind/config.ini', encoding='utf-8')
            for row in selected_rows:
                # 行号+1
                row_number = row + 1
                if not config.has_section('System'):
                    config.add_section('System')
                config.set('System', str(row_number), f'{file_name}')
                Global.G_Game[row].data["config"] = file_name

            with open('bind/config.ini', 'w', encoding='utf-8') as configfile:
                config.write(configfile)

            QMessageBox.information(self, "提示", f"绑定配置成功")

    def on_table_view_double_clicked(self, index):
        self.m_currentRow = index.row()
        self.on_function_setting()
        self.tableView.clearSelection()

    def on_function_setting(self):
        self.configDlg = ConfigDialog(parent=self, m_currentRow=self.m_currentRow)
        self.configDlg.exec()
        self.m_currentRow = -1

    def on_start_script(self):
        if Global.G_Server == None:
            return
        for row in range(self.model.rowCount()):
            item = self.model.item(row, 0)
            if item is not None and item.checkState() == Qt.CheckState.Checked:
                if row < len(Global.G_Game):
                    game_data = Global.G_Game[row]
                    # 检查配置是否存在
                    if not game_data.data["config"]:
                        game_data.data["notes"] = "请绑定配置后再操作"
                        continue
                    if game_data.data["processID"] > 0:
                        data = {}
                        data["method"] = "AutoScript"
                        data["enable"] = True;
                        if Global.G_Server.SendData(row, data):
                            game_data.data["notes"] = "开始执行脚本"
                        else:
                            game_data.data["notes"] = "执行脚本失败"
                    else:
                        game_data.data["notes"] = "请先启动进程"

    def on_stop_script(self):
        for row in range(self.model.rowCount()):
            item = self.model.item(row, 0)
            if item is not None and item.checkState() == Qt.CheckState.Checked:
                if row < len(Global.G_Game):
                    game_data = Global.G_Game[row]
                    # if game_data.data["processID"] >0 :
                    #     data = {}
                    #     data["method"] = "AutoScript"
                    #     data["enable"] = False
                    #     if Global.G_Server.SendData(row, data):
                    #         game_data.data["notes"] = "脚本停止"
                    #     else:
                    #         game_data.data["notes"] = "脚本停止失败"

    def on_api(self):
        dataDlg = DataDialog(parent=self, m_currentRow=self.m_currentRow)
        dataDlg.exec()
        
    def on_action_import(self):
        file_path, _ = QFileDialog.getOpenFileName(self, "选择文件", "", "Text Files (*.txt)")
        if file_path:
            self.table_data_thread = self.TableDataThread(self, file_path)
            self.table_data_thread.start()
            
    def on_action_selectAll(self):
        if hasattr(self, 'model_account') and self.model_account:
            for row in range(self.model_account.rowCount()):
                index = self.model_account.index(row, 0)
                self.model_account.setData(index, Qt.CheckState.Checked.value, Qt.ItemDataRole.CheckStateRole)
                
    def on_action_UnselectAll(self):
        if hasattr(self, 'model_account') and self.model_account:
            for row in range(self.model_account.rowCount()):
                index = self.model_account.index(row, 0)
                self.model_account.setData(index, Qt.CheckState.Unchecked.value, Qt.ItemDataRole.CheckStateRole)
                
    def on_action_del(self):
        if not hasattr(self, 'model_account') or not self.model_account or not hasattr(self, 'cur_btn_key'):
            return
            
        selected_rows = self.model_account.getCheckedRows()
        if not selected_rows:
            QMessageBox.warning(self, "警告", "请先勾选要删除的记录")
            return
            
        reply = QMessageBox.question(
            self,
            '询问',
            f'您确定要删除选中的{len(selected_rows)}条记录吗？此操作不可恢复!',
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
            QMessageBox.StandardButton.No
        )
        
        if reply == QMessageBox.StandardButton.No:
            return
            
        # 显示加载提示
        self.statusBar.showMessage("正在删除账号记录，请稍候...")
        
        try:
            # 特殊处理邮箱账号
            if self.cur_btn_key == '邮箱账号':
                # 收集所有选中行的邮箱地址
                emails = []
                for row in selected_rows:
                    email_index = self.model_account.index(row[0], 1)  # 邮箱地址列
                    email = self.model_account.data(email_index, Qt.ItemDataRole.DisplayRole)
                    if email:
                        emails.append(email)
                    
                    # 取消勾选
                    index = self.model_account.index(row[0], 0)
                    self.model_account.setData(index, Qt.CheckState.Unchecked.value, Qt.ItemDataRole.CheckStateRole)
                
                # 批量删除邮箱账号
                if emails:
                    # 分批处理，每批最多500个
                    batch_size = 500
                    total_deleted = 0
                    
                    for i in range(0, len(emails), batch_size):
                        batch_emails = emails[i:i+batch_size]
                        deleted_count = UserManager.delete_mail_by_names(batch_emails)
                        total_deleted += deleted_count
                        
                    self.statusBar.showMessage(f"删除操作完成：成功删除 {total_deleted} 条邮箱记录", 3000)

                
                # 重新加载当前视图
                QTimer.singleShot(100, lambda: self.refresh_current_account_view())
                return
            
            # 普通账号处理
            # 收集所有选中行的用户名
            usernames = []
            for row in selected_rows:
                username_index = self.model_account.index(row[0], 1)  # 账号列
                username = self.model_account.data(username_index, Qt.ItemDataRole.DisplayRole)
                usernames.append(username)
                
            # 取消所有勾选
            for row in selected_rows:
                index = self.model_account.index(row[0], 0)
                self.model_account.setData(index, Qt.CheckState.Unchecked.value, Qt.ItemDataRole.CheckStateRole)
                
            # 分批处理，每批最多500个
            batch_size = 500
            total_deleted = 0
            
            conn = DbManager.get_conn(for_writing=True)
            if not conn:
                self.statusBar.showMessage("数据库连接失败", 3000)
                return
                
            try:
                cursor = conn.cursor()
                
                # 分批删除
                for i in range(0, len(usernames), batch_size):
                    batch_users = usernames[i:i+batch_size]
                    
                    # 构建IN子句的参数
                    placeholders = ','.join(['?'] * len(batch_users))
                    
                    # 执行批量删除
                    cursor.execute(f"DELETE FROM user_info WHERE user IN ({placeholders})", batch_users)
                    deleted_count = cursor.rowcount
                    total_deleted += deleted_count
                    
                    # 从已使用列表中移除
                    for username in batch_users:
                        if username in UserManager._used_users:
                            UserManager._used_users.remove(username)
                
                conn.commit()
                
                # 清理表格中已删除的行
                self.model_account.clear()
                
                # 显示结果
                self.statusBar.showMessage(f"删除操作完成：成功删除 {total_deleted} 条记录", 3000)
            except Exception as e:
                conn.rollback()
                Global.LOGE(f"批量删除用户失败: {e}")
                self.statusBar.showMessage(f"删除操作失败: {str(e)}", 3000)
            finally:
                DbManager.release_connection(conn)
                
            # 重新加载当前视图
            QTimer.singleShot(100, lambda: self.refresh_current_account_view())
                
        except Exception as e:
            Global.LOGE(f"删除用户失败: {e}")
            self.statusBar.showMessage(f"删除操作失败: {str(e)}", 3000)

    def on_action_clearn(self):
        if not hasattr(self, 'model_account') or not self.model_account or not hasattr(self, 'cur_btn_key'):
            return
            
        # 创建自定义对话框
        dialog = QDialog(self)
        dialog.setWindowTitle('确认清空')
        dialog.setModal(True)
        
        layout = QVBoxLayout()
        label = QLabel(f'<span style="font-size: 14pt; color: red;">确定要清空[{self.cur_btn_key}]的所有数据吗？</span><br><br>请在下方输入框中输入<span style="font-size: 14pt; color: red;">"清空"</span>继续:')
        input_box = QLineEdit()
        
        btn_box = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel)
        btn_box.accepted.connect(dialog.accept)
        btn_box.rejected.connect(dialog.reject)
        
        layout.addWidget(label)
        layout.addWidget(input_box)
        layout.addWidget(btn_box)
        dialog.setLayout(layout)
        
        if dialog.exec() == QDialog.DialogCode.Accepted and input_box.text().strip() == '清空':
            # 显示加载提示
            self.statusBar.showMessage(f"正在清空{self.cur_btn_key}数据，请稍候...")
            
            try:
                # 确定状态对应的标志
                status = None
                conditions = None
                
                # 清空表格数据
                self.model_account.clear()
                
                # 根据当前按钮确定删除条件
                if self.cur_btn_key == '待用账号':
                    status = UserManager.STATUS_UNUSED
                elif self.cur_btn_key == '运行账号':
                    status = UserManager.STATUS_RUNNING
                elif self.cur_btn_key == '成功账号':
                    status = UserManager.STATUS_SUCCESS
                elif self.cur_btn_key == '失败账号':
                    status = UserManager.STATUS_FAILED
                elif self.cur_btn_key == '上传账号':
                    status = UserManager.STATUS_UPLOAD
                elif self.cur_btn_key == '邮箱账号':
                    # 邮箱账号使用mail_info表，使用delete_all参数删除所有记录
                    # 修改UserManager中的delete_mail_by_condition方法，使其支持分批删除
                    deleted_count = UserManager.delete_mail_by_condition(delete_all=True, batch_size=500)
                    if deleted_count > 0:
                        self.statusBar.showMessage(f"清空操作完成：成功删除 {deleted_count} 条邮箱记录", 3000)
                        # 刷新当前视图
                        QTimer.singleShot(100, lambda: self.refresh_mail_view_after_clean())
                    else:
                        self.statusBar.showMessage("邮箱账号表中没有数据可清空", 3000)
                    return
                
                # 执行批量删除
                if status is not None:
                    # 按状态删除，使用batch_size参数进行分批删除
                    deleted_count = UserManager.delete_users_by_condition(status=status)
                    self.statusBar.showMessage(f"清空操作完成：成功删除 {deleted_count} 条记录", 3000)
                else:
                    self.statusBar.showMessage("无法识别的账号类型", 3000)
                
            except Exception as e:
                Global.LOGE(f"清空操作失败: {e}")
                self.statusBar.showMessage(f"清空操作失败: {str(e)}", 3000)
        else:
            QMessageBox.information(self, '提示', '操作已取消')
    def on_action_copy_hang(self):
        """复制选中行数据到剪贴板，字段间用----分隔，行间用换行符分隔"""
        selected_indexes = self.tableView_account.selectionModel().selectedRows()
        if not selected_indexes:
            return
            
        clipboard_text = ""
        headers = self.model_account._headers[1:]  # 跳过第一列序号列

        for row in selected_indexes:
            row_data = []
            for col in range(len(headers)):
                index = self.model_account.index(row.row(), col+1)  # +1跳过序号列
                data = self.model_account.data(index, Qt.ItemDataRole.DisplayRole)
                if isinstance(data,str):
                    row_data.append(str(data) if data else "")
                elif data.isValid():
                    row_data.append("")

            clipboard_text += "----".join(row_data) + "\n"
        
        QApplication.clipboard().setText(clipboard_text.strip())
        #复制选中行


    table_data_signal = pyqtSignal()  # 新增信号用于线程通信
    class TableDataThread(QThread):
        def __init__(self, parent,path,isMenu=False):
            super().__init__(parent)
            self.parent = parent
            self.path =path
            self.isMenu = isMenu
        def run(self):
            try:
                if self.parent.cur_btn_key=='待用账号':
                    if not self.isMenu:
                        self.parent.btn_importAccount.setEnabled(False)
                    #AccountManager.导入账号(self.path)
                    success_count = UserManager.import_users(self.path,self.parent.account_table['fields'])
                    # 使用信号通知账号导入完成
                    self.parent.account_imported_signal.emit()
                    # 显示导入结果
                    if self.isMenu:
                        QMetaObject.invokeMethod(
                            QApplication.instance(), 
                            lambda: QMessageBox.information(None, "导入完成", f"成功导入 {success_count} 条账号记录"),
                            Qt.ConnectionType.QueuedConnection
                        )
                elif self.parent.cur_btn_key=='邮箱账号':
                    #AccountManager.导入邮箱(self.path)
                    success_count = UserManager.import_mail(self.path,self.parent.account_table['mail_fields'])
                    # 使用信号通知邮箱导入完成
                    self.parent.mail_imported_signal.emit()
                    # 显示导入结果
                    if self.isMenu:
                        QMetaObject.invokeMethod(
                            QApplication.instance(), 
                            lambda: QMessageBox.information(None, "导入完成", f"成功导入 {success_count} 条邮箱记录"),
                            Qt.ConnectionType.QueuedConnection
                        )
                if not self.isMenu:
                    self.parent.table_data_signal.emit()
                    #self.parent.btn_importAccount.setEnabled(True)
                
            except Exception as e:
                Global.LOGE(f"导入数据时发生错误: {str(e)}")
                # 在UI线程中显示错误消息
                error_msg = f"导入数据时发生错误: {str(e)}"
                QMetaObject.invokeMethod(QApplication.instance(), lambda: QMessageBox.warning(None, "错误", error_msg), Qt.ConnectionType.QueuedConnection)

    def init_table_data(self, count=0, mode=0):
        try:
            self.tableView.setUpdatesEnabled(False)
            for i, game in enumerate(Global.G_Game):
                if hasattr(game, 'Log'):
                    game.Log.remove(game.LogHandle)
            if mode==0:
                pass
            elif mode == 4:
                Global.G_Game.clear()
                # 使用UserManager获取账号数据，先读取运行账号，不够再读取待用账号
                # UserManager.get_user_info方法已经实现了这个逻辑，并会自动维护已使用账号列表
                account_data = UserManager.get_user_info(count)
                
                if len(account_data) > 0:
                    for user_info in account_data:
                        temp = Global.GameDataStruct()
                        temp.data['user'] = user_info.get('user', '')
                        temp.data['pass'] = user_info.get('pass', '')
                        temp.data['user_id'] = user_info.get('user_id', '')
                        temp.data['token'] = user_info.get('token', '')
                        temp.data['account_info'] = user_info.get('account_info', '')
                        temp.data['upload_id'] = user_info.get('upload_id', '')
                        # 检查是否有邮箱信息
                        if user_info.get('mail') and '@' in user_info.get('mail', ''):
                            temp.data['email'] = user_info.get('mail', '')
                            temp.data['email_pass'] = user_info.get('mail_pass', '')

                            
                        Global.G_Game.append(temp)  # 将temp添加到Global.G_Game中
                        # 为表头的对应列赋值，从第1列开始依次累加
                        self.model._data.append(temp.data)

            elif mode in(1,2):
                Global.G_Game.clear()
                for i in range(count):
                    temp = Global.GameDataStruct()
                    Global.G_Game.append(temp)  # 将temp添加到Global.G_Game中

                    # 为表头的对应列赋值，从第1列开始依次累加
                    row = self.model.rowCount()
                    self.model._data.append(temp.data)

            self.model.layoutChanged.emit()
        except Exception as e:
            QMessageBox.critical(self, "错误", f"初始化表格数据时发生错误: {str(e)}")
        self.tableView.setUpdatesEnabled(True)

    def init_card_data(self):
        """
        从 card.txt 文件中读取卡号数据，并赋值给 G_Game[i].data["cardUser"]
        """
        try:
            if os.path.exists("card.txt"):
                with open("card.txt", "r", encoding="utf-8") as file:
                    lines = file.read().splitlines()
                    for i, line in enumerate(lines):
                        if i < len(Global.G_Game):
                            Global.G_Game[i].data["cardUser"] = line.strip()
        except Exception as e:
            QMessageBox.critical(self, "错误", f"初始化卡号数据时发生错误: {str(e)}")

    # 实现btn_SelectAll按钮的点击事件回调
    def btn_SelectAll_clicked(self):
        for row in range(self.model.rowCount()):
            index = self.model.index(row, 0)
            if index.isValid():
                self.model.setData(index, Qt.CheckState.Checked.value, Qt.ItemDataRole.CheckStateRole)

    # 实现btn_UnSelectAll按钮的点击事件回调
    def btn_UnSelectAll_clicked(self):
        for row in range(self.model.rowCount()):
            index = self.model.index(row, 0)
            if index.isValid():
                self.model.setData(index, Qt.CheckState.Unchecked.value, Qt.ItemDataRole.CheckStateRole)

    def btn_Start_clicked(self):
        mode = self.comboBox_mode.currentData()
        if not mode:
            QMessageBox.warning(self, "提示", "请选择一种模式")
            return
        #if not AccountManager.is_load_complete:
        if not UserManager._is_initialized:
            QMessageBox.warning(self, "提示", "请等待账号数据加载完毕后重试")
            return
        self.btn_Start.setEnabled(False)
        self.btn_Stop.setEnabled(True)
        self.Edit_MaxNum.setEnabled(False)
        self.comboBox_mode.setEnabled(False)
        self.btn_importAccount.setEnabled(False)
        max_num = Global.read_ini(Global.ConfigFileName, 'System', 'maxNum', str(QThread.idealThreadCount()))
        Global.G_ProcessPool.setMaxThreadCount(int(max_num))
        def async_task():
            Global.G_ScriptRunTime = int(time.time())
            if mode in (1, 2, 3, 4):
                self.init_table_view()
                self.init_table_data(int(max_num), mode)

            for row in range(self.model.rowCount()):
                if mode == 1 or mode == 2:
                    if row < len(Global.G_Game):
                        game_data = Global.G_Game[row]
                        if not game_data.isScriptRun:
                            task = ProcessPoolTask(row,mode)
                            Global.G_ProcessPool.start(task)
                else:
                    if row < len(Global.G_Game):
                        game_data = Global.G_Game[row]
                        #ischecked = self.model.data(self.model.index(row, 0), Qt.ItemDataRole.CheckStateRole)
                        if not game_data.isScriptRun :#and ischecked == Qt.CheckState.Checked.value
                            if mode != 1 and len(game_data.data["user"]) == 0:
                                continue
                            task = ProcessPoolTask(row, mode)
                            Global.G_ProcessPool.start(task)

            Global.G_ProcessPool.waitForDone() #等待线程

            self.btn_Start.setEnabled(True)
            self.btn_Stop.setEnabled(False)
            self.Edit_MaxNum.setEnabled(True)
            self.comboBox_mode.setEnabled(True)
            #self.btn_importAccount.setEnabled(True)

        threading.Thread(target=async_task, name="异步任务").start()

    def btn_Stop_clicked(self):
        # 弹出确认对话框
        reply = QMessageBox.question(self, '提示', '当前操作将要关闭进程,请确认是否继续？',
                                     QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No)
        if reply == QMessageBox.StandardButton.No:
            return  # 用户选择不关闭进程
        Global.G_ProcessPool.clear()
        for row in range(self.model.rowCount()):
            if row < len(Global.G_Game):
                game_data = Global.G_Game[row]
                game_data.isScriptRun = False
                game_data.isInBattle = False
                game_data.isRepetition_Battle = False
                if game_data.Game:
                    game_data.Game.Close()
                if game_data.GateWay:
                    game_data.GateWay.Close()

        # 清空黑名单，避免重复跑时因黑名单过大导致速度变慢或无法获取账号
        if hasattr(UserManager, '_used_users') and UserManager._used_users:
            count = len(UserManager._used_users)
            UserManager._used_users.clear()
            #Global.LOGD(f"已清空账号黑名单，共清除 {count} 个账号")
            
        # 清空邮箱黑名单
        if hasattr(UserManager, '_used_emails') and UserManager._used_emails:
            email_count = len(UserManager._used_emails)
            UserManager._used_emails.clear()
            #Global.LOGD(f"已清空邮箱黑名单，共清除 {email_count} 个邮箱")
            
        self.statusBar.showMessage(f"已清空账号和邮箱黑名单", 3000)
        self.btn_Stop.setEnabled(False)
        Global.G_ScriptRunTime = 0

    def on_importAccount_clicked(self):
        #self.init_table_view()
        # 以线程方式调用init_table_data
        # if not AccountManager.is_load_complete:
        #     QMessageBox.warning("提示","请等待账号文件加载完成后重试")
        #     return
        path = self.Edit_Path.text()
        self.table_data_thread = self.TableDataThread(self,path)
        self.table_data_thread.start()
    def update_status_bar(self, updates):
        """处理状态栏更新"""
        if 'total' in updates:
            self.tj_value.setText(updates['total'])
        if 'upload' in updates:
            self.upload_value.setText(updates['upload'])
        if 'hour_produce' in updates:
            self.hour_produce_value.setText(updates['hour_produce'])

    def disable_account_buttons(self):
        """禁用所有账号相关按钮"""
        self.pushButton_RunAccount.setEnabled(False)
        self.pushButton_SuccessAccount.setEnabled(False)
        self.pushButton_FailAccount.setEnabled(False)
        self.pushButton_UploadAccount.setEnabled(False)
        self.pushButton_mailAccount.setEnabled(False)
        
    def enable_account_buttons(self):
        """启用所有账号相关按钮"""
        self.pushButton_UseAccount.setEnabled(True)
        self.pushButton_RunAccount.setEnabled(True)
        self.pushButton_SuccessAccount.setEnabled(True)
        self.pushButton_FailAccount.setEnabled(True)
        self.pushButton_UploadAccount.setEnabled(True)
        self.pushButton_mailAccount.setEnabled(True)
    
    def _do_query_users(self, status, fields, button_obj, button_text, conditions=None):
        """执行用户查询的通用方法，支持可选的条件过滤"""
        try:
            # 执行查询
            处理后数据 = UserManager.get_users(
                status,
                fields=fields,
                conditions=conditions,
                format='list'
            )
            self.model_account.insertRowsWithData(0, 处理后数据)
        except Exception as e:
            Global.LOGE(f"查询用户数据异常: {e}")
        finally:
            # 恢复按钮状态
            button_obj.setText(f"{button_text}({len(处理后数据)})")
            self.enable_account_buttons()
            self.statusBar.clearMessage()
            self._is_loading = False

    def on_UseAccount_clicked(self):
        if self._is_loading:
            return
            
        self._is_loading = True
        
        # 显示加载提示
        self.statusBar.showMessage("正在加载待用账号数据，请稍候...")
        
        # 改变按钮外观，显示正在加载
        old_text = self.pushButton_UseAccount.text()
        self.pushButton_UseAccount.setText("加载中...")
        self.pushButton_UseAccount.setEnabled(False)
        
        # 禁用其他账号相关按钮
        self.disable_account_buttons()
        
        self.model_account.clear()
        self.cur_btn_key = '待用账号'
        self.init_account_table_view()
        # 使用QTimer延迟执行查询，让UI有时间更新
        QTimer.singleShot(10, lambda: self._do_query_users(
            UserManager.STATUS_UNUSED,
            self.account_table['fields'],
            self.pushButton_UseAccount,
            self.cur_btn_key
        ))

    def on_RunAccount_clicked(self):
        if self._is_loading:
            return
            
        self._is_loading = True
        
        # 显示加载提示
        self.statusBar.showMessage("正在加载运行账号数据，请稍候...")
        
        # 改变按钮外观，显示正在加载
        old_text = self.pushButton_RunAccount.text()
        self.pushButton_RunAccount.setText("加载中...")
        self.pushButton_RunAccount.setEnabled(False)
        
        # 禁用其他账号相关按钮
        self.disable_account_buttons()
        
        self.model_account.clear()
        self.cur_btn_key = '运行账号'
        self.init_account_table_view()
        # 使用QTimer延迟执行查询，让UI有时间更新
        QTimer.singleShot(50, lambda: self._do_query_users(
            UserManager.STATUS_RUNNING,
            self.account_table['fields'],
            self.pushButton_RunAccount,
            self.cur_btn_key
        ))

    def on_SuccessAccount_clicked(self):
        if self._is_loading:
            return
            
        self._is_loading = True
        
        # 显示加载提示
        self.statusBar.showMessage("正在加载成功账号数据，请稍候...")
        
        # 改变按钮外观，显示正在加载
        old_text = self.pushButton_SuccessAccount.text()
        self.pushButton_SuccessAccount.setText("加载中...")
        self.pushButton_SuccessAccount.setEnabled(False)
        
        # 禁用其他账号相关按钮
        self.disable_account_buttons()
        
        self.model_account.clear()
        self.cur_btn_key = '成功账号'
        self.init_account_table_view()
        # 使用QTimer延迟执行查询，让UI有时间更新
        QTimer.singleShot(50, lambda: self._do_query_users(
            UserManager.STATUS_SUCCESS,
            self.account_table['fields'],
            self.pushButton_SuccessAccount,
            self.cur_btn_key
        ))

    def on_FailAccount_clicked(self):
        if self._is_loading:
            return

        self._is_loading = True
        
        # 显示加载提示
        self.statusBar.showMessage("正在加载失败账号数据，请稍候...")
        
        # 改变按钮外观，显示正在加载
        old_text = self.pushButton_FailAccount.text()
        self.pushButton_FailAccount.setText("加载中...")
        self.pushButton_FailAccount.setEnabled(False)
        
        # 禁用其他账号相关按钮
        self.disable_account_buttons()
        
        self.model_account.clear()
        self.cur_btn_key = '失败账号'
        self.init_account_table_view()
        # 使用QTimer延迟执行查询，让UI有时间更新
        QTimer.singleShot(50, lambda: self._do_query_users(
            UserManager.STATUS_FAILED,
            self.account_table['fields'],
            self.pushButton_FailAccount,
            self.cur_btn_key
        ))
        
    def on_UploadAccount_clicked(self):
        if self._is_loading:
            return

        self._is_loading = True
        
        # 显示加载提示
        self.statusBar.showMessage("正在加载上传账号数据，请稍候...")
        
        # 改变按钮外观，显示正在加载
        old_text = self.pushButton_UploadAccount.text()
        self.pushButton_UploadAccount.setText("加载中...")
        self.pushButton_UploadAccount.setEnabled(False)
        
        # 禁用其他账号相关按钮
        self.disable_account_buttons()
        
        self.model_account.clear()
        self.cur_btn_key = '上传账号'
        self.init_account_table_view()
        # 使用QTimer延迟执行查询，让UI有时间更新
        QTimer.singleShot(50, lambda: self._do_query_users(
            UserManager.STATUS_UPLOAD,
            self.account_table['fields'],
            self.pushButton_UploadAccount,
            self.cur_btn_key
        ))
        
    def on_mailAccount_clicked(self):
        if self._is_loading:
            return
        self.init_account_table_view()
        self._is_loading = True
        
        # 显示加载提示
        self.statusBar.showMessage("正在加载邮箱账号数据，请稍候...")
        
        # 改变按钮外观，显示正在加载
        old_text = self.pushButton_mailAccount.text()
        self.pushButton_mailAccount.setText("加载中...")
        self.pushButton_mailAccount.setEnabled(False)
        
        # 禁用其他账号相关按钮
        self.disable_account_buttons()
        
        self.model_account.clear()
        self.cur_btn_key = '邮箱账号'
        self.init_account_table_view()
        
        # 使用QTimer延迟执行查询，让UI有时间更新
        QTimer.singleShot(50, lambda: self._do_query_mail_accounts(
            self.account_table['mail_fields'],
            self.pushButton_mailAccount,
            self.cur_btn_key
        ))

    def init_account_table_view(self):
        try:
            if self.model_account != None:
                self.model_account.clear()
            if hasattr(self,"cur_btn_key") and self.cur_btn_key=="邮箱账号":
                self.model_account.setHeaders(self.account_table['mail_header'])
            else:
                self.model_account.setHeaders(self.account_table['header'])
            self.tableView_account.setModel(self.model_account)
            self.tableView_account.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)
            self.tableView_account.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
            self.tableView_account.setAlternatingRowColors(True)
            self.tableView_account.setSelectionMode(QAbstractItemView.SelectionMode.MultiSelection)
            self.tableView_account.verticalHeader().setVisible(False)
            self.tableView_account.horizontalHeader().setStretchLastSection(True)
            self.tableView_account.installEventFilter(self)
            self.tableView_account.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
            self.tableView_account.setColumnWidth(0, 50)  # 设置行号列宽度为50
            self.tableView_account.show()
            self.model_account.setCheckableColumns([0])
        except Exception as e:
            QMessageBox.critical(self, "错误", f"初始化表格视图时发生错误: {str(e)}")

    def handle_account_status_update(self, target_status: int, status_name: str, exclude_key: str):
        """通用的账号状态更新处理函数
        
        Args:
            target_status: 目标状态值
            status_name: 状态名称（用于显示）
            exclude_key: 排除的按钮键（当前状态不能转换为自己）
        """
        if not hasattr(self, 'cur_btn_key') or not self.cur_btn_key or self.cur_btn_key == exclude_key:
            return
            
        selected_rows = self.model_account.getCheckedRows()
        if not selected_rows:
            QMessageBox.warning(self, "警告", "请先勾选要转移的记录")
            return
            
        reply = QMessageBox.question(
            self,  # 父窗口
            '询问',  # 标题
            f'您正在将选中账号转为{status_name}状态，请确认是否继续?',  # 内容
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,  # 按钮
            QMessageBox.StandardButton.No  # 默认选中按钮
        )
        if reply == QMessageBox.StandardButton.No:
            return
            
        # 显示加载提示
        self.statusBar.showMessage("正在更新账号状态，请稍候...")
        
        # 收集所有用户名
        usernames = []
        row_indices = []
        for row in selected_rows:
            try:
                username_index = self.model_account.index(row[0], 1)  # 账号列
                username = self.model_account.data(username_index, Qt.ItemDataRole.DisplayRole)
                usernames.append(username)
                row_indices.append(row[0])
            except Exception as e:
                Global.LOGE(f"获取用户名失败: {e}")
        
        if not usernames:
            return
        
        # 批量更新用户状态
        results = UserManager.batch_update_user_status(usernames, target_status)
        
        success_count = 0
        fail_count = 0
        success_rows = []
        
        # 处理结果并收集需要批量操作的数据
        for i, (row_idx, result) in enumerate(zip(row_indices, results)):
            try:
                if result:
                    success_count += 1
                    success_rows.append(row_idx)
                else:
                    fail_count += 1
            except Exception as e:
                Global.LOGE(f"处理行数据失败: {e}")
                fail_count += 1

        if success_rows:
            self.model_account.batchRemoveRows(success_rows)
                
        # 显示结果
        self.statusBar.showMessage(f"操作完成：成功 {success_count} 条，失败 {fail_count} 条", 3000)
    
    def on_action_useAccount(self):
        """使用账号"""
        self.handle_account_status_update(UserManager.STATUS_UNUSED, "待用", "待用账号")
        


    def on_action_runAccount(self):
        """运行账号"""
        self.handle_account_status_update(UserManager.STATUS_RUNNING, "运行", "运行账号")
        


    def on_action_successAccount(self):
        """成功账号"""
        self.handle_account_status_update(UserManager.STATUS_SUCCESS, "成功", "成功账号")


    def on_action_failAccount(self):
        """失败账号"""
        self.handle_account_status_update(UserManager.STATUS_FAILED, "失败", "失败账号")
        


    def on_action_uploadAccount(self):
        """上传账号"""
        self.handle_account_status_update(UserManager.STATUS_UPLOAD, "上传", "上传账号")


    def refresh_mail_view_after_clean(self):
        """清空邮箱账号后刷新视图（不显示导入成功信息）"""
        try:
            self.statusBar.showMessage("正在刷新邮箱视图...")
            self.cur_btn_key = '邮箱账号'
            self.model_account.clear()
            self.init_account_table_view()
            self._do_query_mail_accounts(
                self.account_table['mail_fields'],
                self.pushButton_mailAccount,
                self.cur_btn_key
            )
        except Exception as e:
            Global.LOGE(f"刷新邮箱视图失败: {e}")
            QMessageBox.warning(self, "错误", f"刷新邮箱视图失败: {str(e)}")
            
    def refresh_mail_view(self):
        """安全地刷新邮箱账号视图，在邮箱导入后调用"""
        try:
            self.statusBar.showMessage("邮箱数据已导入，正在刷新视图...")
            self.cur_btn_key = '邮箱账号'
            self.model_account.clear()
            self.init_account_table_view()
            self._do_query_mail_accounts(
                self.account_table['mail_fields'],
                self.pushButton_mailAccount,
                self.cur_btn_key
            )
            QMessageBox.information(self, "提示", "邮箱数据导入成功")
        except Exception as e:
            Global.LOGE(f"刷新邮箱视图失败: {e}")
            QMessageBox.warning(self, "错误", f"刷新邮箱视图失败: {str(e)}")
            
    def refresh_current_account_view(self):
        """刷新当前账号视图"""
        if self.cur_btn_key == '待用账号':
            self.on_UseAccount_clicked()
        elif self.cur_btn_key == '运行账号':
            self.on_RunAccount_clicked()
        elif self.cur_btn_key == '成功账号':
            self.on_SuccessAccount_clicked()
        elif self.cur_btn_key == '失败账号':
            self.on_FailAccount_clicked()
        elif self.cur_btn_key == '上传账号':
            self.on_UploadAccount_clicked()
        elif self.cur_btn_key == '邮箱账号':
            self.on_mailAccount_clicked()

    def on_action_export_file(self):
        """导出当前视图的数据到文本文件，以----分隔列数据"""
        if not hasattr(self, 'model_account') or not self.model_account or not hasattr(self, 'cur_btn_key') or not self.cur_btn_key:
            QMessageBox.warning(self, "警告", "请先选择要导出的账号类型")
            return
        
        try:
            # 提示用户选择保存文件路径
            save_path, _ = QFileDialog.getSaveFileName(
                self, 
                f"导出{self.cur_btn_key}数据", 
                f"{self.cur_btn_key}.txt", 
                "文本文件 (*.txt)"
            )
            
            if not save_path:
                return  # 用户取消了保存
                
            row_count = self.model_account.rowCount()
            if row_count == 0:
                QMessageBox.information(self, "提示", "没有数据可导出")
                return
                
            # 获取表头（跳过序号列）
            headers = self.model_account._headers[1:]
                
            # 打开文件写入数据
            with open(save_path, 'w', encoding='utf-8') as f:
                # 写入表头（以##开头作为注释）
                f.write("##" + "----".join(headers) + "\n")
                
                # 写入每行数据
                for row in range(row_count):
                    row_data = []
                    for col in range(1, len(self.model_account._headers)):  # 跳过序号列
                        index = self.model_account.index(row, col)
                        value = self.model_account.data(index, Qt.ItemDataRole.DisplayRole)
                        if isinstance(value, str):
                            row_data.append(value if value else "")
                        elif hasattr(value, 'isValid') and value.isValid():
                            row_data.append(str(value))
                        else:
                            row_data.append("")
                            
                    f.write("----".join(row_data) + "\n")
            
            # 导出成功后显示消息
            self.statusBar.showMessage(f"成功导出{row_count}条记录到文件: {save_path}", 5000)
            QMessageBox.information(self, "导出成功", f"成功导出{row_count}条记录到文件:\n{save_path}")
            
        except Exception as e:
            Global.LOGE(f"导出文件失败: {e}")
            QMessageBox.warning(self, "导出失败", f"导出文件失败: {str(e)}")
    def on_action_export_All_Del(self):
        try:
            if not hasattr(self, 'model_account') or not self.model_account or not hasattr(self, 'cur_btn_key') or not self.cur_btn_key:
                QMessageBox.warning(self, "警告", "请先选择要导出的账号类型")
                return

            # 提示用户选择保存文件路径
            save_path, _ = QFileDialog.getSaveFileName(
                self,
                f"导出{self.cur_btn_key}数据",
                f"{self.cur_btn_key}.txt",
                "文本文件 (*.txt)"
            )

            if not save_path:
                return  # 用户取消了保存

            status = None
            if self.cur_btn_key == '待用账号':
                status = UserManager.STATUS_UNUSED
            elif self.cur_btn_key == '运行账号':
                status = UserManager.STATUS_RUNNING
            elif self.cur_btn_key == '成功账号':
                status = UserManager.STATUS_SUCCESS
            elif self.cur_btn_key == '失败账号':
                status = UserManager.STATUS_FAILED
            elif self.cur_btn_key == '上传账号':
                status = UserManager.STATUS_UPLOAD
            elif self.cur_btn_key == '邮箱账号':
                button_info = self.pushButton_mailAccount
                QMessageBox.information(self, "提示", "暂不支持")
                return

            查询结果 = UserManager.get_users(status=status, fields=self.account_table['fields'])
            row_count = len(查询结果)
            if row_count == 0:
                QMessageBox.information(self, "提示", "没有数据可导出")
                return

            # 获取表头（跳过序号列）
            headers = self.model_account._headers[1:]

            # 打开文件写入数据
            with open(save_path, 'w', encoding='utf-8') as f:
                # 写入表头（以##开头作为注释）
                f.write("##" + "----".join(headers) + "\n")

                # 写入每行数据
                for row in range(row_count):
                    row_data = []
                    for col in range(1, len(self.model_account._headers)):  # 跳过序号列
                        index = self.model_account.index(row, col)
                        value = self.model_account.data(index, Qt.ItemDataRole.DisplayRole)
                        if isinstance(value, str):
                            row_data.append(value if value else "")
                        elif hasattr(value, 'isValid') and value.isValid():
                            row_data.append(str(value))
                        else:
                            row_data.append("")

                    f.write("----".join(row_data) + "\n")

            # 导出成功后显示消息
            self.statusBar.showMessage(f"成功导出{row_count}条记录到文件: {save_path}", 3000)

            if status is not None:
                # 按状态删除，使用batch_size参数进行分批删除
                deleted_count = UserManager.delete_users_by_condition(status=status)
                self.statusBar.showMessage(f"清空操作完成：成功删除 {deleted_count} 条记录", 3000)
            QMessageBox.information(self, "导出成功", f"成功导出并删除{row_count}条记录到文件:\n{save_path}")
        except Exception as e:
            Global.LOGE(f"导出文件失败: {e}")
            QMessageBox.warning(self, "导出失败", f"导出文件失败: {str(e)}")
    def refresh_account_view(self):
        """安全地刷新账号视图，在账号导入后调用"""
        try:
            self.statusBar.showMessage("账号数据已导入，正在刷新视图...")
            self.on_UseAccount_clicked()
            QMessageBox.information(self, "提示", "账号数据导入成功")
        except Exception as e:
            Global.LOGE(f"刷新账号视图失败: {e}")
            QMessageBox.warning(self, "错误", f"刷新账号视图失败: {str(e)}")